package c2.cross.business.rank.h;

import c2.advanced.business.common.CommonModule;
import c2.cross.business.rank.CrossRankDao;
import c2.cross.business.rank.data.CrossRankKv;
import cate.common.game.mail.MailCmd;
import cate.common.table.d.GDOperation;
import cate.common.table.res.holy_pet.HolyPetExcel;
import cate.common.table.res.holy_pet.rank.HolyPetRankRow;
import cate.common.util.TimeTool;
import cate.game.rank.po.Rank;
import cate.game.res.holy_pet.HolyPetConstants;
import cp.solution.business.game.component.NoticeParam;
import easy.java.dev.note.NoteField;

import java.util.Collections;
import java.util.List;

/**
 * 灵宠跨服排行处理
 *
 * @author ShenSL
 * @since 2023/8/26 16:46
 */
public class HolyPetSupportRankHandler extends BaseSingleValueRankHandler {
    @NoteField("跨服排行存储数据")
    private final CrossRankKv rankKv;
    @NoteField("配置")
    private final HolyPetExcel table;
    @NoteField("公共模块")
    private final CommonModule common;

    public HolyPetSupportRankHandler(int rankId,
                                     CrossRankDao dao,
                                     CrossRankKv kv,
                                     HolyPetExcel table,
                                     CommonModule common) {
        super(rankId, dao);
        this.rankKv = kv;
        this.table = table;
        this.common = common;
    }

    @Override
    protected String getTag() {
        return "holy_pet";
    }

    @Override
    protected int getRankNum() {
        return 100;
    }

    @Override
    public void tick() {
        long nowTime = System.currentTimeMillis();
        if (TimeTool.isDifferentWeek(nowTime, rankKv.getHolyPetLastResetTime())) {
            reset();
            rankKv.setHolyPetLastResetTime(nowTime);
        }
        super.tick();
    }

    /**
     * 结算重置
     */
    private synchronized void reset() {
        List<Rank> rankList = getRankList(0);
        // 发放奖励
        for (int i = 0; i < rankList.size(); i++) {
            int rank = i + 1;
            Rank rankData = rankList.get(i);
            HolyPetRankRow rankRow = table.rank.getList().stream().filter(row -> row.rankStart <= rank && row.rankEnd >= rank)
                    .findAny().orElse(null);
            if (rankRow == null) {
                continue;
            }
            MailCmd mailCmd = new MailCmd().addRole(rankData.owner.uid)
                    .withSrvId(rankData.owner.base.srvId)
                    .withOpr(GDOperation.HOLY_PET_SUPPORT_RANK_REWARD, rank)
                    .withContent(HolyPetConstants.RANK_MAIL_ID,
                            Collections.singletonList(new NoticeParam(NoticeParam.NoticeType.STRING, rank)))
                    .withReward(rankRow.rewardStr);
            common.sendMail(mailCmd);
        }
        clear();
    }
}
